package com.zdft.promotion;

import java.util.IdentityHashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.PlatformTransactionManager;

import com.baomidou.mybatisplus.extension.incrementer.OracleKeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.zdft.promotion.common.dao.ds.DSRoute;
import com.zdft.promotion.common.dao.ds.DynamicDataSource;
import com.zdft.promotion.common.util.rpc.RpcClient;

@Configuration
@EnableScheduling
@EnableCaching
@MapperScan("com.zdft.promotion.**.mapper")
public class ServiceAutoConfiguration {
    // ---------------------------- DB相关配置 -----------------------------
    @Bean(name = "promotionDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.sbom")
    public DataSource getwarehouseDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "erpDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.erp")
    public DataSource getErpDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 动态数据源: 通过AOP在不同数据源之间动态切换
     */
    @Primary
    @Bean(name = "dataSource")
    public DataSource getDatasource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(getwarehouseDataSource());
        // 配置多数据源
        Map<Object, Object> dsCtxt = new IdentityHashMap<>();
        dsCtxt.put(DSRoute.PROMOTION, getwarehouseDataSource());
        dsCtxt.put(DSRoute.ERP, getErpDataSource());

        dynamicDataSource.setTargetDataSources(dsCtxt);
        return dynamicDataSource;
    }


    @Bean
    public PlatformTransactionManager getTransactionManager() {
        return new DataSourceTransactionManager(getDatasource());
    }


    /**
     * mybatisplus 生成通过序列自增
     */
    @Bean
    public OracleKeyGenerator oracleKeyGenerator() {
        return new OracleKeyGenerator();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLimit(100);
        return paginationInterceptor;
    }

}
